<template>
  <div>
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="searchForm" inline>
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="角色标识">
          <el-input v-model="searchForm.roleKey" placeholder="请输入角色标识" clearable />
        </el-form-item>
        <el-form-item label="状态" style="width: 200px;">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="role-management">
      <!-- 操作按钮 -->
      <div class="action-container">
        <el-button type="primary"  v-permission="'admin:basic/role:add'" @click="handleAdd">新增</el-button>
        <el-button type="danger" v-permission="'admin:basic/role:del'" :disabled="!selectedRows.length" @click="handleBatchDelete">
          批量删除
        </el-button>
      </div>

      <!-- 角色表格 -->
      <div class="table-container">
        <el-table
          :data="tableData"
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="role_name" label="角色名称" min-width="120" />
          <el-table-column prop="role_key" label="角色标识" min-width="120" />
          <el-table-column prop="role_sort" label="排序" width="80" />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status ? 'success' : 'danger'">
                {{ row.status ? '启用' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
          <el-table-column prop="create_time" label="创建时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" v-permission="'admin:basic/role:edit'" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="primary" v-permission="'admin:basic/role:permission'" link @click="handleSetPermission(row)">权限</el-button>
              <el-button type="danger" v-permission="'admin:basic/role:del'" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 添加/编辑角色对话框 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
        :close-on-click-modal="false"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色标识" prop="roleKey">
            <el-input v-model="formData.roleKey" placeholder="请输入角色标识" />
          </el-form-item>
          <el-form-item label="排序" prop="roleSort">
            <el-input-number v-model="formData.roleSort" :min="0" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </template>
      </el-dialog>

      <!-- 权限设置对话框 -->
      <el-dialog
        title="权限设置"
        v-model="permissionDialogVisible"
        width="700px"
        :close-on-click-modal="false"
      >
        <div class="permission-container">
          <el-tree
            ref="menuTreeRef"
            :data="menuTreeData"
            show-checkbox
            node-key="id"
            :props="treeProps"
            :default-checked-keys="checkedMenuKeys"
            :check-strictly="isCheckStrictly"
            @check="handleCheck"
          />
        </div>
        <template #footer>
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermission" :loading="submitting">
            保存
          </el-button>
        </template>
      </el-dialog>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type ElTree } from 'element-plus'
import type { RoleItem, RoleForm, MenuItem } from '@/types/role'
import {
  getRoleList,
  getRoleDetail,
  addRole,
  updateRole,
  updateRole2,
  deleteRole,
  getMenuTree
} from '@/api/role'
import { convertKeysToSnakeCase } from '@/utils/caseConverter'

// 搜索表单
const searchForm = reactive({
  roleName: '',
  roleKey: '',
  status: ''
})

// 表格数据
const tableData = ref<RoleItem[]>([])
const loading = ref(false)
const selectedRows = ref<RoleItem[]>([])

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const dialogTitle = ref('')
const submitting = ref(false)

// 表单引用
const formRef = ref<FormInstance>()
const menuTreeRef = ref<InstanceType<typeof ElTree>>()

// 表单数据
const formData = reactive<RoleForm>({
  roleName: '',
  roleKey: '',
  roleSort: 0,
  status: 1,
  remark: '',
  menuIds: []
})

// 表单验证规则
const formRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  roleKey: [
    { required: true, message: '请输入角色标识', trigger: 'blur' }
  ],
  roleSort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 菜单树数据
const menuTreeData = ref<MenuItem[]>([])
const checkedMenuKeys = ref<number[]>([])
const currentRole = ref<RoleItem>()

// 在现有代码中添加一个新的属性配置
const treeProps = {
  children: 'children',
  label: 'title'
}

const isCheckStrictly = ref(true) // 初始为严格模式用于回显

// 处理复选框点击事件
const handleCheck = () => {
  // 确保在非严格模式下进行选择
  isCheckStrictly.value = false
}

// 初始化数据
onMounted(() => {
  nextTick(() => {
    // 回显完成后，切换到非严格模式用于后续点选
    isCheckStrictly.value = false
  })
  loadTableData()
  loadMenuTree()
})

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.current,
      size: pagination.size
    }
    const result = await getRoleList(params)
    tableData.value = result.data.list
    pagination.total = result.data.total
  } catch (error) {
    console.error('加载角色列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载菜单树
const loadMenuTree = async () => {
  try {
    console.log('开始加载菜单树...')
    const result = await getMenuTree()
    console.log('菜单树原始数据:', result)
    
    // 确保数据结构正确
    menuTreeData.value = Array.isArray(result.data) ? result.data : []
    
    if (menuTreeData.value.length === 0) {
      console.warn('菜单树数据为空')
      ElMessage.warning('菜单数据为空，请检查后端接口')
    } else {
      console.log('菜单树加载成功，数据条数:', menuTreeData.value.length)
    }
  } catch (error) {
    console.error('加载菜单树失败:', error)
    ElMessage.error('加载菜单权限失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadTableData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    roleName: '',
    roleKey: '',
    status: ''
  })
  handleSearch()
}

// 选择行
const handleSelectionChange = (rows: RoleItem[]) => {
  selectedRows.value = rows
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadTableData()
}

// 当前页改变
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadTableData()
}

// 新增角色
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  dialogVisible.value = true
  nextTick(() => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    Object.assign(formData, {
      roleName: '',
      roleKey: '',
      roleSort: 0,
      status: 1,
      remark: '',
      menuIds: []
    })
  })
}

// 编辑角色
const handleEdit = async (row: RoleItem) => {
  if(row.id === 1){
    ElMessage.error('超级管理员角色不能编辑')
    return false
  }
  dialogTitle.value = '编辑角色'
  dialogVisible.value = true
  try {
    const detail = await getRoleDetail(row.id!)
    Object.assign(formData, {
      id: detail.data.id,
      roleName: detail.data.role_name,
      roleKey: detail.data.role_key,
      roleSort: detail.data.role_sort.toString(),
      status: detail.data.status,
      remark: detail.data.remark || '',
      menuIds: detail.data.menu_ids,
      createTime: detail.data.create_time,
      updateTime: detail.data.update_time
    });
    console.log(formData);
  } catch (error) {
    console.error('获取角色详情失败:', error)
    ElMessage.error('获取角色详情失败')
  }
}



// 修改 handleSetPermission 中的相关部分
const handleSetPermission = async (row: RoleItem) => {
  currentRole.value = row
  permissionDialogVisible.value = true
  try {
    
    const detail = await getRoleDetail(row.id!)
    checkedMenuKeys.value = detail.data.menu_ids || []

    nextTick(() => {
      if (menuTreeRef.value) {
        menuTreeRef.value.setCheckedKeys(checkedMenuKeys.value)
      }
    })
  } catch (error) {
    console.error('获取角色权限失败:', error)
    ElMessage.error('获取角色权限失败')
  }
}

// 修改 handleSavePermission 中的相关部分
const handleSavePermission = async () => {
  if (!menuTreeRef.value || !currentRole.value) return

  try {
    submitting.value = true
    
    nextTick(async () => {
      const checkedKeys = menuTreeRef.value!.getCheckedKeys(false) as number[]
      const menuIds = [...checkedKeys]

      const payload: Partial<RoleForm> & { id: number } = {
        id: currentRole.value?.id!,
        menuIds: menuIds
      }

      await updateRole2(payload as RoleForm)

      ElMessage.success('权限设置成功')
      permissionDialogVisible.value = false
    })
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存权限失败')
  } finally {
    submitting.value = false
  }
}


// 删除角色
const handleDelete = async (row: RoleItem) => {
  try {
    if(row.id === 1){
      ElMessage.error('超级管理员角色不能删除')
      return false
    }


    await ElMessageBox.confirm(`确定删除角色吗？`, '提示', {
      type: 'warning'
    })
    await deleteRole(row.id!)
    ElMessage.success('删除成功')
    loadTableData()
  } catch (error) {
    console.error('删除角色失败:', error)
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedRows.value.length) return
  
  try {
    await ElMessageBox.confirm(`确定删除选中的${selectedRows.value.length}个角色吗？`, '提示', {
      type: 'warning'
    })
    
    const ids = selectedRows.value.map(item => item.id!)
    // 这里可以调用批量删除接口
    for (const id of ids) {
      await deleteRole(id)
    }
    
    ElMessage.success('删除成功')
    selectedRows.value = []
    loadTableData()
  } catch (error) {
    console.error('批量删除失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (formData.id) {
      let json = convertKeysToSnakeCase(formData)
      await updateRole(json)
      ElMessage.success('更新成功')
    } else {
      let json = convertKeysToSnakeCase(formData)
      await addRole(json)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    loadTableData()
  } catch (error:any) {
    console.error('提交表单失败:', error)
    if(error.code == 500||error.code == 400){
      ElMessage.error(error.message)
    }
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.search-container {
  background: #f5f7fa;
  padding: 20px;
  margin-bottom: 1px;
  border-radius: 4px;
}

.action-container {
  background: #fff;
  padding: 6px 10px;
  margin-bottom: 1px;
  border-radius: 4px;
}

.table-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 10px;
  text-align: right;
}

.permission-container {
  max-height: 400px;
  overflow-y: auto;
}
</style>